package org.bjf.utils;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * map工具
 */
@Slf4j
public class MapUtil {

    /**
     * 根据对象取Map,空值跳过
     */
    public static Map<String, String> toMap(Object obj, boolean ignoreNull) {
        Class clz = obj.getClass();
        //====1.取当前类字段
        Map<String, String> fieldMap = getFieldMap(obj, clz.getDeclaredFields(), ignoreNull);

        //====2.取父类字段
        Map<String, String> supperFieldMap = getFieldMap(obj, clz.getSuperclass().getDeclaredFields(),
                ignoreNull);

        fieldMap.putAll(supperFieldMap);

        return fieldMap;
    }

    private static Map<String, String> getFieldMap(Object obj, Field[] fields, boolean ignoreNull) {
        Map<String, String> params = new HashMap<>();
        //====1.取当前类字段
        for (Field field : fields) {
            try {
                field.setAccessible(Boolean.TRUE);
                Object value = field.get(obj);
                // 空值跳过
                if (value == null || field.isAnnotationPresent(JsonIgnore.class)) {
                    if (ignoreNull) {
                        continue;
                    } else {
                        value = "";
                    }
                }
                // 取字段别名
                String name = field.getName();
                if (field.isAnnotationPresent(JSONField.class)) {
                    JSONField jsonField = field.getAnnotation(JSONField.class);
                    String aliasName = jsonField.name();
                    if (StringUtils.isNotBlank(aliasName)) {
                        name = aliasName;
                    }
                }
                params.put(name, String.valueOf(value));
            } catch (IllegalAccessException e) {
                log.error(e.getMessage(), e);
            }
        }
        return params;
    }

}
